﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ZhongKeSite.Common;
using ZhongKeSite.Common.Helper;
using ZhongKeSite.Entity;

namespace ZhongKeSite.FileResources.Controllers
{
    public class FileController : Controller
    {
        private readonly IPathProvider _pathProvider;
        public FileController(IPathProvider pathProvider)
        {
            _pathProvider = pathProvider;
        }

        #region 获取文件
        [HttpGet]
        public IActionResult Doc(string id, string name = "")
        {
            try
            {
                #region 参数校验
                if (string.IsNullOrWhiteSpace(id))
                {
                    return Json(new { retStatus = 400, retMsg = "无效参数" });
                }
                string paras = DESEncrypt.Decrypt(id, DESEncrypt.Key);
                if (string.IsNullOrWhiteSpace(paras))
                {
                    return Json(new { retStatus = 401, retMsg = "无效参数" });
                }
                List<string> list = paras.Split('&').ToList();
                if (list.Count != 2)
                {
                    return Json(new { retStatus = 400, retMsg = "无效参数" });
                }
                string FilePath = list[0];
                if (string.IsNullOrWhiteSpace(FilePath))
                {
                    return Json(new { retStatus = 401, retMsg = "无效参数" });
                }
                string dtStr = list[1];
                DateTime dt = DateTime.MinValue;
                if (!DateTime.TryParse(dtStr, out dt))
                {
                    return Json(new { retStatus = 401, retMsg = "无效参数" });
                }
                TimeSpan ts = DateTime.Now - dt;
                if (ts.TotalMinutes > 60)
                {
                    return Json(new { retStatus = 401, retMsg = "链接过期" });
                }
                #endregion

                string Extension = Path.GetExtension(FilePath).ToLower();
                string contentType = "image/jpeg";
                switch (Extension)
                {
                    case ".pdf":
                        contentType = "application/pdf";
                        break;
                    case ".xls":
                        contentType = "application/vnd.ms-excel";
                        break;
                    case ".xlsx":
                        contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                        break;
                    case ".doc":
                        contentType = "application/msword";
                        break;
                    case ".docx":
                        contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                        break;
                }
                if (string.IsNullOrEmpty(contentType))
                {
                    return Json(new { retStatus = 401, retMsg = "无效文件类型" });
                }

                string path = _pathProvider.MapPath(FilePath);

                if (!System.IO.File.Exists(path))
                {
                    return Json(new { retStatus = 500, retMsg = "找不到不对应的文件" });
                }

                var FileBytes = System.IO.File.ReadAllBytes(path);

                if (!Request.IsMobileBrowser() && ".pdf".EqualsIgnoreCase(Extension))
                {
                    if (!string.IsNullOrWhiteSpace(name))
                    {
                        return File(FileBytes, contentType, name);
                    }
                    else
                    {
                        return File(FileBytes, contentType);
                    }
                }
                else
                {
                    if (Extension.Equals(".jpg") || Extension.Equals(".png") || Extension.Equals(".jpeg"))
                    {
                        return File(FileBytes, "image/jpeg");
                    }
                    else
                    {
                        if (!string.IsNullOrWhiteSpace(name))
                        {
                            return File(FileBytes, contentType, name);
                        }
                        else
                        {
                            return File(FileBytes, contentType, IdentityCreator.NextIdentity + Extension);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return Json(new { retStatus = 500, retMsg = "获取文件异常", exMsg = ex.Message });
            }
        }
        #endregion

        #region 异常页面
        public IActionResult Error()
        {
            return View();
        }
        #endregion

        #region  上传文件
        [HttpPost]
        public async Task<ResultResponse<UploadFileInfo>> UploadFiles(IFormCollection formCollection)
        {
            ResultResponse<UploadFileInfo> resultResponse = new ResultResponse<UploadFileInfo> { success = false, code = -1, msg = "上传失败" };
            try
            {
                FormFileCollection filelist = (FormFileCollection)formCollection.Files;
                if (filelist.Count < 1)
                {
                    resultResponse.msg = "请求中未包含任何上传文件，请检查";
                    return resultResponse;
                }

                Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
                foreach (var item in formCollection)
                {
                    keyValuePairs.Add(item.Key, item.Value);
                }

                string uploadFileType = keyValuePairs.ContainsKey("UploadFileType") ? keyValuePairs["UploadFileType"] : string.Empty;
                string userId = keyValuePairs.ContainsKey("UserId") ? keyValuePairs["UserId"] : "";
                string token = keyValuePairs.ContainsKey("Token") ? keyValuePairs["Token"] : "";
                string FileName = keyValuePairs.ContainsKey("UFileName") ? keyValuePairs["UFileName"] : IdentityCreator.NextIdentity;//保存到服务器文件时的名称

                if (string.IsNullOrWhiteSpace(token))
                {
                    resultResponse.msg = "请求参数无效";
                    return resultResponse;
                }

                string tokenValue = DESEncrypt.Decrypt(token, DESEncrypt.Key);
                if (string.IsNullOrEmpty(tokenValue))
                {
                    resultResponse.msg = "请求参数无效";
                    return resultResponse;
                }

                if (string.IsNullOrWhiteSpace(uploadFileType))
                {
                    resultResponse.msg = "请求中未包含上传文件类型，请传递文件类型参数";
                    return resultResponse;
                }
                string TempPath = string.Empty;

                var FileType = EnumHelper.GetEnumByName<UploadFileType>(uploadFileType);
                switch (FileType)
                {
                    case UploadFileType.IconImage:
                        TempPath = string.Format("/Files/Users/{0}/IconImage/", userId);
                        break;
                    case UploadFileType.CoverImage:
                        TempPath = string.Format("/Files/Users/{0}/CoverImage/", userId);
                        break;
                    case UploadFileType.ProductDetailImage:
                        TempPath = string.Format("/Files/Users/{0}/ProductDetailImage/", userId);
                        break;
                    case UploadFileType.NewsImage:
                        TempPath = string.Format("/Files/Users/{0}/NewsImage/", userId);
                        break;
                    case UploadFileType.AdImage:
                        TempPath = string.Format("/Files/Users/{0}/AdImage/", userId);
                        break;
                }

                var file = filelist.FirstOrDefault();
                string name = file.FileName;
                string FilePath = _pathProvider.MapPath(TempPath);

                long FileSize = file.Length / 1024;

                string Extension = Path.GetExtension(name);
                DirectoryInfo directoryInfo = new DirectoryInfo(FilePath);
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }

                string DiskPath = string.Concat(FilePath, FileName, Extension);
                using (var fs = new FileStream(DiskPath, FileMode.Create, FileAccess.Write))
                {
                    await file.CopyToAsync(fs);
                    await fs.FlushAsync();
                    fs.Close();
                }

                string FileMime = Extension.ToUpper();
                string DiskCompressPath = string.Concat(FilePath, FileName, "_Compress", Extension);
                string SavePath = TempPath + FileName + Extension;

                //图片质量压缩
                if (FileMime.Equals(".JPG") || FileMime.Equals(".PNG") || FileMime.Equals(".JPEG"))
                {
                    bool CompressFlag = FileHelper.CompressImage(DiskPath, DiskCompressPath, 90, 1024);
                    if (CompressFlag)
                    {
                        SavePath = string.Concat(TempPath, FileName, "_Compress", Extension);
                    }
                }

                UploadFileInfo fileInfo = new UploadFileInfo
                {
                    FileName = FileName + Extension,
                    FilePath = SavePath,
                    FileSize = FileSize,
                    FileMime = FileMime.Replace(".", "")
                };

                resultResponse.data = fileInfo;
                resultResponse.success = true;
                resultResponse.msg = "上传成功";
                resultResponse.code = 1;
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                resultResponse.msg = ex.Message;
            }
            return resultResponse;
        }
        #endregion

    }
}
